package com.xinghou.platform.service.main.impl;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.tools.json.JSONUtil;
import com.xinghou.platform.dao.main.*;
import com.xinghou.platform.entity.req.UserRegistReq;
import com.xinghou.platform.model.main.*;
import com.xinghou.platform.server.mq.MqMessage;
import com.xinghou.platform.service.main.UserService;
import com.xinghou.platform.util.DateUtils;
import com.xinghou.platform.util.HttpUtils;
import com.xinghou.platform.util.JsonUtil;
import com.xinghou.platform.util.StringUtils;
import com.xinghou.platform.util.exception.DBExceptionEnums;
import com.xinghou.platform.util.exception.ExceptionEnums;
import com.xinghou.platform.util.exception.ServiceException;
import javapns.org.json.HTTP;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;

@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource
    private UserGeoDAO userGeoDAO;
    @Resource
    private UserAppDAO userAppDAO;
    @Resource
    private UserStatisticsDAO userStatisticsDAO;
    @Resource
    private UserDAO userDAO;
    @Resource
    private InterestTagsDAO interestTagsDAO;
    @Resource
    private StoreDAO storeDAO;
    @Resource
    private CityDAO cityDAO;
    @Resource
    private ProvinceDAO provinceDAO;
    @Resource
    private MqMessage mqMessage;
    @Resource
    private UserService userService;

    private String huanxinUrl = "https://a1.easemob.com/xinghou-service/xinghou/users";

    @Override
    public String createUserAccount(UserRegistReq userRegistReq) {
        // TODO Auto-generated method stub
        try {

            User user = new User();
            Long nowdate=System.currentTimeMillis();
            user.setPhonenumber(userRegistReq.getMobile());
            user.setPassword(userRegistReq.getPwd());

            user.setRegstatus((short) 1);
            user.setOstype(Short.valueOf("0"));
            user.setUsertype(Short.valueOf("0"));
            user.setHeadstatus(Short.valueOf("0"));
            user.setStatus(Short.valueOf("0"));
            user.setSex(Short.valueOf("0"));
            user.setCreatetime(System.currentTimeMillis());

            user.setQqstate(0);
            user.setWbstate(0);
            user.setWxstate(0);
            if (StringUtils.isNotBlank(userRegistReq.getType().toString())) {
                if (!userRegistReq.getType().equals("mobile") && !userRegistReq.getType().equals("account")) {
                    if (userRegistReq.getType().equals("QQ")) {
                        user.setQqid(userRegistReq.getSecondaccount());
                        user.setQqstate(1);
                    } else if (userRegistReq.getType().equals("WB")) {
                        user.setWbid(userRegistReq.getSecondaccount());
                        user.setWbstate(1);
                    } else {
                        user.setWxid(userRegistReq.getSecondaccount());
                        user.setWxstate(1);
                    }
                }
            }
            if(!StringUtils.isEmpty(userRegistReq.getUasystem())){
                user.setPlatform(Integer.parseInt(userRegistReq.getUasystem()));
            }
            int userid = userDAO.saveUser(user);
            UserGeo usergeo = new UserGeo();
            usergeo.setGeoId(userid);
            usergeo.setCreateTime(nowdate);
            userGeoDAO.saveUserGeo(usergeo);

            UserApp userapp = new UserApp();
            userapp.setCreateTime(nowdate);
            userapp.setRegistVersion(userRegistReq.getAppversion());
            //userapp.setVersion(userRegistReq.getAppversion());
            userapp.setAppId(userid);
            userAppDAO.saveUserApp(userapp);

            UserStatistics userstat = new UserStatistics();
            userstat.setLogincount(0);
            userstat.setDynamiccount(0);
            userstat.setFanscount(0);
            userstat.setLastlogintime(nowdate);
            userstat.setPraisecount(0);
            userstat.setUpdatetime(nowdate);
            userstat.setAttentioncount(0);
            userstat.setCreatetime(nowdate);
            userstat.setVisitcount(0);
            userstat.setSalecount(0);
            userstat.setBuycount(0);
            userstat.setProductcount(0);
            userstat.setProjectcount(0);
            userstat.setExposurecount(0);
            userstat.setStatid(userid);
            userStatisticsDAO.saveUserStat(userstat);
            return "0";
        } catch (Exception e) {
            e.printStackTrace();
            return "1";
        }
    }

    @Override
    public String updateUserInfoBase(UserRegistReq userRegist)
            throws DataAccessException {
        int userid = Integer.parseInt(userRegist.getUserid());
        try {
            User user = userDAO.getUserById(userid);
            if(user==null) {
                throw new ServiceException(DBExceptionEnums.USER_IS_NULL);
            }
            if(!StringUtils.isEmpty(userRegist.getMobile())) {
               if(isMobileBind(userRegist.getMobile()))
                   throw  new ServiceException(DBExceptionEnums.PASSWORD_HAS_BIND);
                user.setPhonenumber(userRegist.getMobile());
            }
            if(!StringUtils.isEmpty(userRegist.getTaste())) {
                user.setTaste(userRegist.getTaste());
                userService.updateUserInfoTaste(userRegist);
            }
            if(!StringUtils.isEmpty(userRegist.getArea()))
            user.setAdcode(userRegist.getArea());
            if(!StringUtils.isEmpty(userRegist.getHeadurl()))
            user.setHeadurl(userRegist.getHeadurl());
            if(!StringUtils.isEmpty(userRegist.getNickname()))
                user.setNickname(URLDecoder.decode(userRegist.getNickname(), "UTF-8"));
            String sex = userRegist.getSex();
            if(!StringUtils.isEmpty(userRegist.getAgeyear()))
            user.setAgeyear(userRegist.getAgeyear());
            if(!StringUtils.isEmpty(userRegist.getSex()))
            user.setSex(new Short(sex));
            if(!StringUtils.isEmpty(userRegist.getIntr()))
            user.setSignature(userRegist.getIntr());
            if(!StringUtils.isEmpty(userRegist.getHeadurl()))
            user.setHeadurl(userRegist.getHeadurl());
            if(!StringUtils.isEmpty(userRegist.getPwd()))
                user.setPassword(userRegist.getPwd());
            int n1 = userDAO.updateUser(user);
            mqMessage.sendMessageUser(user.getUserid()+"",true);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "1";
    }






    @Override
    public String updateUserInfoTaste(UserRegistReq userRegist)
            throws DataAccessException {
        int userid = Integer.parseInt(userRegist.getUserid());
        int num = interestTagsDAO.delInterestTags(userid);
        if (num < 0) {
            return "1";
        }
        String taste = userRegist.getTaste();
        String[] arr = taste.split("-");
        for (int i = 0; i < arr.length; i++) {
            InterestTags tag = new InterestTags();
            tag.setUserId(userid);
            tag.setTagId(Integer.parseInt(arr[i]));
            interestTagsDAO.saveInterestTags(tag);
        }
        return "";
    }

    @Override
    public String updateUserInfoJob(UserRegistReq userRegist)
            throws DataAccessException {
        int userid = Integer.parseInt(userRegist.getUserid());

        User user = userDAO.getUserById(userid);
        if (userRegist.getSftype().equals("1"))
            user.setUsertype((short) 0);
        else
            user.setUsertype((short) 1);

        if (user.getRegstatus() < 4)
            user.setRegstatus((short) 4);

        if (StringUtils.isBlank(userRegist.getSignatures())) {
            //默认更新签名
            if (user.getUsertype() == 1) {
                userRegist.setSignatures("你的美丽，我来缔造");
            } else {
                if (user.getSex() == 0) {
                    userRegist.setSignatures("万千倾慕中，我尊贵如后");
                } else {
                    userRegist.setSignatures("与爱美的女孩做朋友");
                }
            }
            user.setSignature(userRegist.getSignatures());
        } else {
            user.setSignature(userRegist.getSignatures());
        }

        int n1 = userDAO.updateUser(user);

        //userLuceneService.updateUserInfo(user, userInfo);

        if (n1 > 0)

            return "0";
        else {
            return "1";
        }
    }

    @Override
    public String updateUserInfoShop(UserRegistReq userRegist)
            throws DataAccessException {
        int userid = Integer.parseInt(userRegist.getUserid());

        User user = userDAO.getUserById(userid);
        if (StringUtils.isBlank(userRegist.getShopid())) {
            Store store = new Store();
            store.setName(userRegist.getShopname());
            int storeid = storeDAO.saveStore(store);
            user.setName(userRegist.getShopjob());
            user.setStoreid(storeid);
            user.setUpdatetime(System.currentTimeMillis());
            if (user.getRegstatus() < 5) {
                user.setRegstatus((short) 5);
            }
            userDAO.updateUser(user);

            return "0";
        } else {
            user.setName(userRegist.getShopjob());
            user.setStoreid(Integer.valueOf(userRegist.getShopid()));
            user.setUpdatetime(System.currentTimeMillis());
            if (user.getRegstatus() < 5) {
                user.setRegstatus((short) 5);
            }
            userDAO.updateUser(user);

            return "0";
        }
    }

    @Override
    public String registerHuanxin(Integer uid, String password, String nickname) {
        HashMap map = new HashMap();
        map.put("username", uid.toString());
        map.put("password", password);
        String result="";
        try {
            result= HttpUtils.sendSSLPostRequest(huanxinUrl,map);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(DBExceptionEnums.SERVER_INTEERFACE_ERROR);
        }
        String app=JSON.parseObject(result).getString("application");
        return null;
    }

    @Override
    public Boolean isMobileBind(String mobile) {
       int count=userDAO.getMobileCount(mobile);
        if(count>0)
            return true;
        else return  false;
    }

}
